package pl.gpms.server.persistance.dao;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import pl.gpms.client.dto.ObjectsDTO;
import pl.gpms.server.persistance.map.Objects;
import pl.gpms.server.persistance.tools.HibernateUtil;

public class ObjectsDao implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	public List<ObjectsDTO> getListOfAllObjects() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		List<Objects> objectList = new ArrayList<Objects>(session.createQuery("from Objects").list());
		List<ObjectsDTO> objectListDTO = new ArrayList<ObjectsDTO>(objectList != null ? objectList.size() : 0);
		if(objectList != null) {
			for (Objects objects : objectList) {
				objectListDTO.add(createObjectsDTO(objects));
			}
		}
		session.getTransaction().commit();
		session.close();
		return objectListDTO;
	}
	
	public Long saveNewObject(ObjectsDTO objectDTO) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Objects object = new Objects(objectDTO);
		Long generatedId = (Long) session.save(object);
		session.getTransaction().commit();
		session.close();
		System.out.println("generatedId: " + generatedId);
		return generatedId;
	}
	
	public ObjectsDTO createObjectsDTO(Objects objects) {
		
		DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
		
		return new ObjectsDTO(objects.getName(), 
				             objects.getName2(), 
				             objects.getAttrib(), 
				             formatter.format(objects.getDate()),
				             objects.getId());
	}
}
